<template>
  <div class="w-full max-w-md">
    <form @submit.prevent="handleRegister" class="rounded-xl overflow-hidden transform transition-all duration-500 hover:shadow-xl bg-white/90 backdrop-blur-sm">
      <div class="px-8 pt-8 pb-6">
        <h2 class="text-2xl font-bold text-transparent bg-clip-text bg-gradient-to-r from-[#93dc24] to-[#8153ff] mb-6 text-center animate-fade-in-up" style="--delay: 100ms;">创建账号</h2>
        
        <!-- 用户名输入框 -->
        <div class="mb-5 group animate-fade-in-up" style="--delay: 200ms;">
          <label for="username" class="block text-sm font-medium text-gray-700 mb-1 group-focus-within:text-[#93dc24] transition-colors duration-300">用户名</label>
          <div class="relative">
            <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none text-gray-400 group-focus-within:text-[#93dc24] transition-colors duration-300">
              <font-awesome-icon icon="user" class="transform group-focus-within:scale-110 transition-all duration-300" />
            </div>
            <input
              id="username"
              v-model="username"
              type="text"
              required
              class="form-input pl-10 w-full px-3 py-3.5 border border-gray-300 rounded-xl shadow-sm focus:outline-none focus:ring-2 focus:ring-[#93dc24]/60 focus:border-[#93dc24] transition-all duration-500 ease-spring"
              placeholder="请输入您的用户名"
              :class="{ 'border-red-500 focus:ring-red-500 focus:border-red-500': errors.username }"
            />
            <div v-if="username" 
                class="absolute inset-y-0 right-0 pr-3 flex items-center cursor-pointer opacity-0 group-hover:opacity-100 transition-opacity duration-200"
                @click="username = ''">
              <font-awesome-icon icon="times-circle" class="text-gray-400 hover:text-[#93dc24] transition-colors duration-300 transform hover:scale-110" />
            </div>
          </div>
          <p v-if="errors.username" class="mt-1 text-sm text-red-500 flex items-center animate-fade-in">
            <font-awesome-icon icon="exclamation-circle" class="mr-1" />
            {{ errors.username }}
          </p>
        </div>
        
        <!-- 邮箱输入框 -->
        <div class="mb-5 group animate-fade-in-up" style="--delay: 300ms;">
          <label for="email" class="block text-sm font-medium text-gray-700 mb-1 group-focus-within:text-[#93dc24] transition-colors duration-300">邮箱</label>
          <div class="relative">
            <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none text-gray-400 group-focus-within:text-[#93dc24] transition-colors duration-300">
              <font-awesome-icon icon="envelope" class="transform group-focus-within:scale-110 transition-all duration-300" />
            </div>
            <input
              id="email"
              v-model="email"
              type="email"
              required
              class="form-input pl-10 w-full px-3 py-3.5 border border-gray-300 rounded-xl shadow-sm focus:outline-none focus:ring-2 focus:ring-[#93dc24]/60 focus:border-[#93dc24] transition-all duration-500 ease-spring"
              placeholder="请输入您的邮箱"
              :class="{ 'border-red-500 focus:ring-red-500 focus:border-red-500': errors.email }"
            />
            <div v-if="email" 
                class="absolute inset-y-0 right-0 pr-3 flex items-center cursor-pointer opacity-0 group-hover:opacity-100 transition-opacity duration-200"
                @click="email = ''">
              <font-awesome-icon icon="times-circle" class="text-gray-400 hover:text-[#93dc24] transition-colors duration-300 transform hover:scale-110" />
            </div>
          </div>
          <p v-if="errors.email" class="mt-1 text-sm text-red-500 flex items-center animate-fade-in">
            <font-awesome-icon icon="exclamation-circle" class="mr-1" />
            {{ errors.email }}
          </p>
        </div>
        
        <!-- 密码输入框 -->
        <div class="mb-5 group animate-fade-in-up" style="--delay: 400ms;">
          <label for="password" class="block text-sm font-medium text-gray-700 mb-1 group-focus-within:text-[#93dc24] transition-colors duration-300">密码</label>
          <div class="relative">
            <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none text-gray-400 group-focus-within:text-[#93dc24] transition-colors duration-300">
              <font-awesome-icon icon="lock" class="transform group-focus-within:scale-110 transition-all duration-300" />
            </div>
            <input
              id="password"
              v-model="password"
              :type="showPassword ? 'text' : 'password'"
              required
              class="form-input pl-10 w-full px-3 py-3.5 border border-gray-300 rounded-xl shadow-sm focus:outline-none focus:ring-2 focus:ring-[#93dc24]/60 focus:border-[#93dc24] transition-all duration-500 ease-spring"
              placeholder="请设置您的密码"
              :class="{ 'border-red-500 focus:ring-red-500 focus:border-red-500': errors.password }"
            />
            <div 
              class="absolute inset-y-0 right-0 pr-3 flex items-center cursor-pointer"
              @click="togglePasswordVisibility"
            >
              <font-awesome-icon 
                :icon="showPassword ? 'eye-slash' : 'eye'" 
                class="text-gray-400 hover:text-[#93dc24] transition-colors duration-300 transform hover:scale-110"
              />
            </div>
          </div>
          <p v-if="errors.password" class="mt-1 text-sm text-red-500 flex items-center animate-fade-in">
            <font-awesome-icon icon="exclamation-circle" class="mr-1" />
            {{ errors.password }}
          </p>
          <!-- 密码强度指示器 -->
          <div v-if="password && !errors.password" class="mt-2 animate-fade-in">
            <div class="flex items-center">
              <span class="text-xs text-gray-500 w-24">密码强度:</span>
              <div class="flex-1 bg-gray-200 rounded-full h-2 overflow-hidden">
                <div 
                  class="h-full rounded-full transition-all duration-500 ease-spring"
                  :class="[
                    passwordStrength === 'weak' ? 'w-1/3 bg-red-500' : 
                    passwordStrength === 'medium' ? 'w-2/3 bg-[#93dc24]' : 
                    'w-full bg-gradient-to-r from-[#93dc24] to-[#8153ff]'
                  ]"
                ></div>
              </div>
              <span 
                class="ml-2 text-xs font-medium"
                :class="[
                  passwordStrength === 'weak' ? 'text-red-500' : 
                  passwordStrength === 'medium' ? 'text-[#93dc24]' : 
                  'text-[#8153ff]'
                ]"
              >
                {{ 
                  passwordStrength === 'weak' ? '弱' : 
                  passwordStrength === 'medium' ? '中' : 
                  '强' 
                }}
              </span>
            </div>
          </div>
        </div>
        
        <!-- 确认密码输入框 -->
        <div class="mb-6 group animate-fade-in-up" style="--delay: 500ms;">
          <label for="confirmPassword" class="block text-sm font-medium text-gray-700 mb-1 group-focus-within:text-[#93dc24] transition-colors duration-300">确认密码</label>
          <div class="relative">
            <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none text-gray-400 group-focus-within:text-[#93dc24] transition-colors duration-300">
              <font-awesome-icon icon="lock" class="transform group-focus-within:scale-110 transition-all duration-300" />
            </div>
            <input
              id="confirmPassword"
              v-model="confirmPassword"
              :type="showConfirmPassword ? 'text' : 'password'"
              required
              class="form-input pl-10 w-full px-3 py-3.5 border border-gray-300 rounded-xl shadow-sm focus:outline-none focus:ring-2 focus:ring-[#93dc24]/60 focus:border-[#93dc24] transition-all duration-500 ease-spring"
              placeholder="请再次输入密码"
              :class="{ 'border-red-500 focus:ring-red-500 focus:border-red-500': errors.confirmPassword }"
            />
            <div 
              class="absolute inset-y-0 right-0 pr-3 flex items-center cursor-pointer"
              @click="toggleConfirmPasswordVisibility"
            >
              <font-awesome-icon 
                :icon="showConfirmPassword ? 'eye-slash' : 'eye'" 
                class="text-gray-400 hover:text-[#93dc24] transition-colors duration-300 transform hover:scale-110"
              />
            </div>
            <!-- 密码匹配指示器 -->
            <div v-if="password && confirmPassword && password === confirmPassword && !errors.confirmPassword" 
                 class="absolute -right-6 top-1/2 transform -translate-y-1/2 animate-pulse-once">
              <font-awesome-icon icon="check-circle" class="text-[#93dc24]" />
            </div>
          </div>
          <p v-if="errors.confirmPassword" class="mt-1 text-sm text-red-500 flex items-center animate-fade-in">
            <font-awesome-icon icon="exclamation-circle" class="mr-1" />
            {{ errors.confirmPassword }}
          </p>
        </div>
        
        <!-- 用户协议 -->
        <div class="mb-6 animate-fade-in-up" style="--delay: 600ms;">
          <div class="flex items-start">
            <div class="flex items-center h-5">
              <div class="relative">
                <input
                  id="terms"
                  v-model="agreeToTerms"
                  type="checkbox"
                  required
                  class="h-4 w-4 rounded border-gray-300 text-[#8153ff] focus:ring-[#8153ff] transition-colors duration-300 cursor-pointer opacity-0 absolute"
                  :class="{ 'border-red-500': errors.terms }"
                />
                <div class="w-4 h-4 border-2 border-gray-300 rounded flex items-center justify-center bg-white transition-colors duration-300"
                     :class="{ 'border-[#8153ff] bg-[#8153ff]/10': agreeToTerms, 'border-red-500': errors.terms }">
                  <font-awesome-icon 
                    v-if="agreeToTerms" 
                    icon="check" 
                    class="text-[#8153ff] text-xs transform transition-all duration-500 ease-bounce scale-0" 
                    :class="{ 'scale-110': agreeToTerms }" 
                  />
                </div>
              </div>
            </div>
            <div class="ml-3 text-sm">
              <label for="terms" class="font-medium text-gray-700 cursor-pointer">我同意</label>
              <a href="#" class="text-[#8153ff] hover:text-[#93dc24] transition-all duration-300 relative group">
                服务条款
                <span class="absolute bottom-0 left-0 w-0 h-0.5 bg-[#93dc24] group-hover:w-full transition-all duration-300 ease-spring opacity-70"></span>
              </a>
              <span class="text-gray-700">和</span>
              <a href="#" class="text-[#8153ff] hover:text-[#93dc24] transition-all duration-300 relative group">
                隐私政策
                <span class="absolute bottom-0 left-0 w-0 h-0.5 bg-[#93dc24] group-hover:w-full transition-all duration-300 ease-spring opacity-70"></span>
              </a>
            </div>
          </div>
          <p v-if="errors.terms" class="mt-1 text-sm text-red-500 flex items-center animate-fade-in">
            <font-awesome-icon icon="exclamation-circle" class="mr-1" />
            {{ errors.terms }}
          </p>
        </div>
        
        <!-- 注册按钮 -->
        <button
          type="submit"
          class="w-full flex justify-center items-center px-4 py-3.5 bg-gradient-to-r from-[#93dc24] to-[#8153ff] text-white rounded-xl shadow-md hover:shadow-lg focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-[#93dc24] transition-all duration-500 transform hover:translate-y-[-2px] active:translate-y-[1px] group overflow-hidden relative animate-fade-in-up ease-spring"
          :disabled="isLoading"
          style="--delay: 700ms;"
        >
          <span class="absolute inset-0 w-full h-full bg-gradient-to-r from-[#8153ff] to-[#93dc24] opacity-0 group-hover:opacity-100 transition-opacity duration-500"></span>
          <span v-if="isLoading" class="mr-2 relative z-10">
            <svg class="animate-spin h-5 w-5 text-white" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
              <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
              <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
            </svg>
          </span>
          <font-awesome-icon v-else icon="user-plus" class="mr-2 relative z-10 group-hover:scale-110 transition-transform duration-300" />
          <span class="relative z-10">
            {{ isLoading ? '注册中...' : '注册' }}
            <span v-if="!isLoading" class="absolute bottom-0 left-0 w-0 border-b-2 border-white group-hover:w-full transition-all duration-500 ease-spring"></span>
          </span>
        </button>
      </div>
      
      <!-- 登录链接 -->
      <div class="px-8 py-5 border-t border-gray-100/50 flex justify-center animate-fade-in-up" style="--delay: 800ms;">
        <p class="text-sm text-gray-600">
          已有账号?
          <router-link to="/login" class="font-medium text-[#93dc24] hover:text-[#8153ff] transition-all duration-300 relative group">
            立即登录
            <span class="absolute bottom-0 left-0 w-0 h-0.5 bg-[#8153ff] group-hover:w-full transition-all duration-300 ease-spring opacity-70"></span>
          </router-link>
        </p>
      </div>
    </form>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue';
import { useRouter } from 'vue-router';
import { useUserStore } from '../../stores/userStore';
import { authAPI } from '../../services/api';
import { toast } from '../../services/toastService';

const router = useRouter();
const userStore = useUserStore();

// 表单数据
const username = ref('');
const email = ref('');
const password = ref('');
const confirmPassword = ref('');
const agreeToTerms = ref(false);
const showPassword = ref(false);
const showConfirmPassword = ref(false);
const isLoading = ref(false);
const errors = reactive({
  username: '',
  email: '',
  password: '',
  confirmPassword: '',
  terms: '',
  server: ''
});

// 切换密码可见性
const togglePasswordVisibility = () => {
  showPassword.value = !showPassword.value;
};

const toggleConfirmPasswordVisibility = () => {
  showConfirmPassword.value = !showConfirmPassword.value;
};

// 密码强度计算
const passwordStrength = computed(() => {
  if (!password.value) return '';
  
  const hasLowerCase = /[a-z]/.test(password.value);
  const hasUpperCase = /[A-Z]/.test(password.value);
  const hasNumber = /\d/.test(password.value);
  const hasSpecialChar = /[!@#$%^&*(),.?":{}|<>]/.test(password.value);
  const length = password.value.length;
  
  const score = [hasLowerCase, hasUpperCase, hasNumber, hasSpecialChar]
    .filter(Boolean).length;
  
  if (length < 8) return 'weak';
  if (score <= 2) return 'medium';
  return 'strong';
});

// 表单验证
const validateForm = () => {
  let isValid = true;
  
  // 重置错误
  errors.username = '';
  errors.email = '';
  errors.password = '';
  errors.confirmPassword = '';
  errors.terms = '';
  errors.server = '';
  
  // 验证用户名
  if (!username.value) {
    errors.username = '请输入用户名';
    isValid = false;
  } else if (username.value.length < 3) {
    errors.username = '用户名长度不能少于3个字符';
    isValid = false;
  }
  
  // 验证邮箱
  if (!email.value) {
    errors.email = '请输入邮箱';
    isValid = false;
  } else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email.value)) {
    errors.email = '请输入有效的邮箱地址';
    isValid = false;
  }
  
  // 验证密码
  if (!password.value) {
    errors.password = '请输入密码';
    isValid = false;
  } else if (password.value.length < 6) {
    errors.password = '密码长度不能少于6个字符';
    isValid = false;
  }
  
  // 验证确认密码
  if (!confirmPassword.value) {
    errors.confirmPassword = '请确认密码';
    isValid = false;
  } else if (confirmPassword.value !== password.value) {
    errors.confirmPassword = '两次输入的密码不一致';
    isValid = false;
  }
  
  // 验证服务条款
  if (!agreeToTerms.value) {
    errors.terms = '必须同意服务条款和隐私政策';
    isValid = false;
  }
  
  return isValid;
};

// 处理注册
const handleRegister = async () => {
  if (!validateForm()) return;
  
  try {
    isLoading.value = true;
    
    const response = await authAPI.register({
      username: username.value,
      email: email.value,
      password: password.value
    });
    
    // 注册用户 - 使用更新后的方法，传递token参数
    userStore.registerUser({
      id: response.user.id,
      username: response.user.username,
      email: response.user.email
    }, response.token);
    
    // 显示成功消息
    toast.success('注册成功！正在跳转到主页...', 2000);
    
    // 注册成功后重定向到首页
    setTimeout(() => {
      router.push('/home');
    }, 1500);
  } catch (error) {
    console.error('注册失败:', error);
    const errorMsg = error.message || '注册失败，请稍后再试';
    // 显示错误弹窗
    toast.error(errorMsg, 4000);
    errors.server = errorMsg;
  } finally {
    isLoading.value = false;
  }
};
</script>

<style scoped>
/* 表单整体样式 */
form {
  box-shadow: 0 8px 30px rgba(0, 0, 0, 0.05);
  border: 1px solid rgba(255, 255, 255, 0.3);
  transition: all 0.5s cubic-bezier(0.34, 1.56, 0.64, 1);
}

form:hover {
  box-shadow: 0 15px 60px rgba(147, 220, 36, 0.15);
  transform: translateY(-5px);
}

/* 输入框焦点缩放效果 */
.form-input:focus {
  transform: scale(1.01);
  box-shadow: 0 0 15px rgba(147, 220, 36, 0.15);
}

/* 按钮禁用状态 */
button:disabled {
  @apply opacity-70 cursor-not-allowed transform-none shadow-none;
}

/* 自定义复选框动画 */
.ease-bounce {
  transition-timing-function: cubic-bezier(0.175, 0.885, 0.32, 1.275);
}

/* 使输入label在输入框聚焦时变色 */
.group:focus-within label {
  @apply text-[#93dc24];
}

/* 弹性动画 */
.ease-spring {
  transition-timing-function: cubic-bezier(0.34, 1.56, 0.64, 1);
}

/* 淡入动画 */
.animate-fade-in-up {
  opacity: 0;
  transform: translateY(15px);
  animation: fade-in-up 0.8s cubic-bezier(0.34, 1.56, 0.64, 1) forwards;
  animation-delay: var(--delay, 0ms);
}

@keyframes fade-in-up {
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.animate-fade-in {
  animation: fade-in 0.3s ease forwards;
}

@keyframes fade-in {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

/* 单次脉冲动画 */
.animate-pulse-once {
  animation: pulse-once 0.5s cubic-bezier(0.34, 1.56, 0.64, 1) forwards;
}

@keyframes pulse-once {
  0% {
    opacity: 0;
    transform: translate(-50%, -50%) scale(0);
  }
  50% {
    opacity: 1;
    transform: translate(-50%, -50%) scale(1.2);
  }
  100% {
    opacity: 1;
    transform: translate(-50%, -50%) scale(1);
  }
}
</style> 